package smri;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Eduardo
 */
public class SM {

    private int option;        
    private Index index;

    public SM()
    {
        this.index = new Index();
    }

    

    public void menu()
    {
        while(option != 6)
        {
            System.out.println("\nMenu de Opciones:");
            System.out.println("1->Aniadir nuevo fichero.");
            System.out.println("2->Mostrar indice.");
            System.out.println("3->Buscar.");            
            System.out.println("4->Guardar indice en disco.");
            System.out.println("5->Cargar indice de disco");
            System.out.println("6->Salir.");
            System.out.print("Indique una opcion: ");

            try {
                BufferedReader bf = new BufferedReader (new InputStreamReader(System.in));
                option = Integer.parseInt(bf.readLine());
            }
            catch (IOException ex) {
                ex.printStackTrace();
            }

            switch (option)
            {
                case 1:
                    this.addFile();
                    break;
                case 2:                    
                    System.out.println("CONTENIDO DEL INDICE\n");
                    String indexToString = index.toString();
                    if(indexToString.length() == 0)
                        System.out.println("EL INDICE ESTA VACIO!!!");
                    else
                        System.out.println(indexToString);
                    break;
                case 3:
                    this.search();
                    break;                
                case 4:
                    index.saveIndex();
                    break;
                case 5:                    
                    index.loadIndex();
                    System.out.println(index.toString());
                    break;
                 case 6:
                    System.out.println("Saliendo del SMRI...\n");
                    break;
                default:
                    System.out.println("\n!!! Opcion incorrecta\n");
                    break;
            }
        }
    }


    private void addFile()
    {
        System.out.println("\n\nANIADIENDO NUEVO FICHERO AL INDICE");
        System.out.print("Nombre del Fichero(en carpeta Data): ");
       
        String fileName = "";
        try {
            BufferedReader bf = new BufferedReader (new InputStreamReader(System.in));
            fileName = bf.readLine();
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
        

        try
        {
            //Leemos el fichero completo y lo metemos en un string para poderlo separar en documentos
            BufferedReader bf = new BufferedReader(new FileReader("Data\\" + fileName));
            String text = "";
            String sText;

            while((sText = bf.readLine()) != null)
                text = text + sText;

            //Cada ".I" es un nuevo documento, asi que delimitamos por el
            StringTokenizer sTokenizer = new StringTokenizer(text, "I");
            sTokenizer.nextToken();  //Este lee lo que esta antes de la I, que es un punto
            
            while(sTokenizer.hasMoreTokens())
            {                
                sText = sTokenizer.nextToken();
                System.out.println("TOKEN: " + sText);

                Document doc = new Document();
                doc.setFileName(fileName);                

                //Aniadimos el Id al documento
                int posId = sText.indexOf(".");
                System.out.println("ID: " + sText.substring(0, posId).trim());
                doc.setId(Integer.parseInt(sText.substring(0, posId).trim()));
                sText = sText.substring(posId+2);

                //Aniadimos el titulo al documento
                int posTittle = sText.indexOf(".");
                System.out.println("TITTLE: " + sText.substring(0, posTittle).trim());
                doc.setTittle(sText.substring(0, posTittle));
                sText = sText.substring(posTittle+2);

                //Aniadimos el texto del documento
                doc.setText(sText.substring(0, sText.length()-2));
                index.addDocumentToIndex(doc);
                
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

    private void search()
    {
        System.out.println("\n\nBUSCANDO...");
        System.out.print("Introduce la palabra: ");

        String searchWord = "";
        try {
            BufferedReader bf = new BufferedReader (new InputStreamReader(System.in));
            searchWord = bf.readLine();
            searchWord = searchWord.toLowerCase();
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }

        ArrayList<IndexItem> docList = index.search(searchWord);
        if(docList != null)
        {
            for(IndexItem item : docList)
            {
                System.out.println("DOC " + item.getDocReference() + " POS " + item.getCharPosition());
            }
        }
        else
            System.out.println("No existen coincidencias");
    }
    
}
